const util = require('../../../../utils/util')

Page({
  data: {
    activeTab: 'ongoing', // 'ongoing' 或 'completed'
    orderList: [],
    loading: true,
    adminInfo: null
  },
  
  onLoad() {
    this.checkAdminLogin();
  },
  
  onShow() {
    if (this.data.adminInfo) {
      this.loadOrderList();
    }
  },
  
  // 检查管理员登录
  async checkAdminLogin() {
    const adminInfo = wx.getStorageSync('adminInfo');
    const adminToken = wx.getStorageSync('adminToken');
    
    if (!adminInfo || !adminToken) {
      this.redirectToLogin();
      return;
    }
    
    try {
      // 检查管理员身份是否有效
      const result = await wx.cloud.callFunction({
        name: 'checkAdminAuth',
        data: {
          adminId: adminInfo.adminId,
          token: adminToken
        }
      });
      
      const { code, data, message } = result.result;
      
      if (code === 0 && data) {
        // 验证通过，设置管理员信息
        this.setData({
          adminInfo: {
            ...adminInfo,
            ...data
          }
        });
        
        // 加载订单列表
        this.loadOrderList();
      } else {
        // 验证失败，清除存储的信息并重定向到登录页
        wx.removeStorageSync('adminInfo');
        wx.removeStorageSync('adminToken');
        
        wx.showToast({
          title: message || '登录已过期，请重新登录',
          icon: 'none'
        });
        
        this.redirectToLogin();
      }
    } catch (error) {
      console.error('验证管理员身份错误', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
      this.redirectToLogin();
    }
  },
  
  // 切换标签页
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
    this.loadOrderList();
  },
  
  // 加载订单列表
  async loadOrderList() {
    const { activeTab, adminInfo } = this.data;
    this.setData({ loading: true });
    
    try {
      const adminToken = wx.getStorageSync('adminToken');
      const result = await wx.cloud.callFunction({
        name: 'adminGetOrders',
        data: {
          status: activeTab,
          adminId: adminInfo.adminId,
          token: adminToken
        }
      });
      
      const { code, data, message } = result.result;
      
      if (code === 0 && data) {
        // 格式化日期和图片URL
        const orderList = data.map(order => {
          // 处理装备图片
          if (order.equipment) {
            order.equipment.imageUrl = util.formatImageUrl(order.equipment.imageUrl);
          }
          
          // 处理用户头像
          if (order.userInfo) {
            order.userInfo.avatarUrl = util.formatImageUrl(order.userInfo.avatarUrl || '/assets/images/banner1.jpg');
          }
          
          return {
            ...order,
            borrowTimeFormat: util.formatTime(order.borrowTime),
            returnDeadlineFormat: util.formatTime(order.returnDeadline),
            actualReturnTimeFormat: order.actualReturnTime ? util.formatTime(order.actualReturnTime) : ''
          };
        });
        
        this.setData({
          orderList
        });
      } else {
        wx.showToast({
          title: message || '获取订单列表失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('获取订单列表失败', error);
      wx.showToast({
        title: '获取订单列表失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },
  
  // 处理订单操作
  handleOrder(e) {
    const { id, action } = e.currentTarget.dataset;
    
    if (action === 'confirm_return') {
      this.confirmReturn(id);
    } else if (action === 'cancel') {
      this.cancelOrder(id);
    }
  },
  
  // 确认归还
  async confirmReturn(orderId) {
    wx.showModal({
      title: '确认归还',
      content: '确认此订单装备已归还？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const adminToken = wx.getStorageSync('adminToken');
            const result = await wx.cloud.callFunction({
              name: 'adminConfirmReturn',
              data: {
                orderId,
                adminId: this.data.adminInfo.adminId,
                token: adminToken
              }
            });
            
            const { code, message } = result.result;
            
            if (code === 0) {
              wx.showToast({
                title: '确认归还成功',
                icon: 'success'
              });
              
              // 重新加载订单列表
              this.loadOrderList();
            } else {
              wx.showToast({
                title: message || '确认归还失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('确认归还失败', error);
            wx.showToast({
              title: '确认归还失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },
  
  // 取消订单
  async cancelOrder(orderId) {
    wx.showModal({
      title: '取消订单',
      content: '确认取消此订单？',
      success: async (res) => {
        if (res.confirm) {
          try {
            const adminToken = wx.getStorageSync('adminToken');
            const result = await wx.cloud.callFunction({
              name: 'adminCancelOrder',
              data: {
                orderId,
                adminId: this.data.adminInfo.adminId,
                token: adminToken
              }
            });
            
            const { code, message } = result.result;
            
            if (code === 0) {
              wx.showToast({
                title: '取消订单成功',
                icon: 'success'
              });
              
              // 重新加载订单列表
              this.loadOrderList();
            } else {
              wx.showToast({
                title: message || '取消订单失败',
                icon: 'none'
              });
            }
          } catch (error) {
            console.error('取消订单失败', error);
            wx.showToast({
              title: '取消订单失败',
              icon: 'none'
            });
          }
        }
      }
    });
  },
  
  // 查看用户信息
  viewUserInfo(e) {
    const { id } = e.currentTarget.dataset;
    // 在实际项目中可以跳转到用户详情页面
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },
  
  // 重定向到登录页
  redirectToLogin() {
    wx.redirectTo({
      url: '/pages/admin/login/login',
    });
  },
  
  // 返回管理后台首页
  navigateBack() {
    wx.navigateBack();
  }
}) 